<template>
  <div class="mainDiv">
    <el-container class="main_container">
       <el-main>
         <el-form ref="form" :model="form" :rules="rules" label-width="130px">
            <el-row :gutter="15">
              <el-col :span="16">
                <el-card style="margin-bottom: 15px;">
                  <div slot="header" class="clearfix">
                    <span>线路信息</span>
                  </div>
                   <el-row :gutter="15">
                     <el-col :span="8">
                       <el-form-item label="承运商" prop="carrierId">
                         <el-select v-model="form.carrierId" placeholder="请选择承运商" style="width:100%" :disabled="!form.isShow">
                           <el-option
                             v-for="item in carrierOptions"
                             :key="item.id"
                             :label="item.nickName"
                             :value="item.id"
                           />
                         </el-select>
                       </el-form-item>
                     </el-col>

                    <!-- <el-col :span="8">
                       <el-form-item label="部门" prop="deptId">
                         <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择部门"
                         style="width: 100%" size="small" />
                       </el-form-item>
                     </el-col> -->

                     <el-col :span="8">
                       <el-form-item label="线路名称" prop="name">
                         <el-input v-model="form.name" placeholder="请输入线路名称" />
                       </el-form-item>
                     </el-col>
                     <el-col :span="8">
                       <el-form-item label="类型">
                         <el-radio-group v-model="form.type">
                           <el-radio v-for="dict in dict.type.tms_line_type" :key="dict.value" :label="dict.value">{{dict.label}}
                           </el-radio>
                         </el-radio-group>
                       </el-form-item>
                     </el-col>
                   </el-row>
                   <el-row :gutter="15">
                     <el-col :span="8">
                        <el-form-item label="取件人" prop="status">
                          <el-select v-model="form.pickupId" placeholder="请选择取件人">
                            <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName"
                              :value="item.userId"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                         <el-form-item label="派送人" prop="status">
                           <el-select v-model="form.dispatchId" placeholder="请选择派送人">
                             <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName"
                               :value="item.userId"></el-option>
                           </el-select>
                         </el-form-item>
                       </el-col>

                    <!-- <el-col :span="8">
                       <el-form-item label="状态" prop="status">
                         <el-select v-model="form.status" placeholder="请选择状态">
                           <el-option v-for="dict in dict.type.sys_common_status" :key="dict.value" :label="dict.label"
                             :value="dict.value"></el-option>
                         </el-select>
                       </el-form-item>
                     </el-col> -->
                   </el-row>
                </el-card>
                <el-card>
                  <div slot="header" class="clearfix">
                    <span>线路规划</span>
                    <el-button style="float: right; padding: 3px 0" type="text" @click="addLinePoi">新增</el-button>
                  </div>
                  <el-table v-loading="loading" :data="form.linePois" border stripe>
                    <el-table-column label="名称" prop="name">
                      <template slot-scope="scope">
                        <el-input placeholder="名称" v-model="scope.row.name"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="地址" prop="address" width="300">
                      <template slot-scope="scope">
                        <el-autocomplete placeholder="地址"
                        style="width: 100%;"
                        v-model="scope.row.address"
                         :fetch-suggestions="addressSearch"
                         value-key="addr"
                         @select="addressSelect($event,scope.row)"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="联系人" prop="lng">
                      <template slot-scope="scope">
                        <el-input placeholder="联系人" v-model="scope.row.contacts"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="联系方式" prop="lat">
                      <template slot-scope="scope">
                        <el-input placeholder="联系方式" v-model="scope.row.tel"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="类型" prop="type">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.type">
                          <el-option value="0" key="0" label="起点"/>
                          <el-option value="1" key="1" label="途径点"/>
                          <el-option value="2" key="2" label="目的地"/>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="取件人" prop="pickupId">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.pickupId" placeholder="请选择取件人">
                          <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName"
                            :value="item.userId"></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="派送人" prop="dispatchId">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.dispatchId" placeholder="请选择派送人">
                          <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName"
                            :value="item.userId"></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="delLinePoi(scope)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </el-col>
              <el-col :span="8">
                <amap-driving-line :lineArray="markerList" ref="amap"></amap-driving-line>
              </el-col>
            </el-row>
         </el-form>
       </el-main>
       <el-footer>
         <div class="footerDivClass">
           <el-button type="primary" @click="submitForm">确 定</el-button>
           <el-button @click="close()">取 消</el-button>
         </div>
       </el-footer>
    </el-container>
  </div>
</template>

<script>
  import {
    initBean,
    getLines,
    addLines,
    updateLines
  } from "@/api/tms/lines";
  import {delLinePoi} from '@/api/tms/linePoi'
  import {listAddress} from '@/api/tms/address'
  import {listCarrier} from '@/api/tms/carrier';
  import {treeselect} from '@/api/system/dept';
  import {listUser} from '@/api/system/user'
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import AmapDrivingLine from "@/components/AmapDrivingLine";
  import AmapInput from "@/components/AmapInput";
  export default {
    dicts: ['tms_line_type', 'sys_common_status', 'sys_del_flag'],
    components: {
        Treeselect,
        AmapDrivingLine,
        AmapInput
    },
    data(){
      return{
        carrierOptions:[],
        deptOptions:[],
        addressOptions:[],
        userOptions:[],

        // 表单参数
        form: {},

        // 遮罩层
        loading: false,

        selectLon: "",//地址选择后获取的经度传参
        selectLat: "",//地址选择后获取的纬度传参

        markerList:[],

        // 表单校验
        rules: {
          carrierId: [{
            required: true,
            message: "承运商ID不能为空",
            trigger: "blur"
          }],
          deptId: [{
            required: true,
            message: "部门ID不能为空",
            trigger: "blur"
          }],
          name: [{
            required: true,
            message: "线路名称不能为空",
            trigger: "blur"
          }],
          type: [{
            required: true,
            message: "类型不能为空",
            trigger: "blur"
          }],
        }
      }
    },
    created() {
      this.getCarrier();
      this.getTreeselect();
      this.getAddress();
      this.getUsers();
      const id = this.$router.currentRoute.params.id;
      if(id != undefined && id != ''){
        this.getLinesInfo(id)
      }else{
        this.getInit();
      }
    },
    methods:{
      getInit(){
        initBean().then(response=>{
          this.form = response.data;
        })
      },
      getLinesInfo(id){
        getLines(id).then(response=>{
          this.form = response.data;
          this.drawDriving(this.form.linePois)

        })
      },
      /**查询承运商列表 */
      getCarrier(){
        listCarrier().then(response=>{
          this.carrierOptions = response.rows;
        })
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
          treeselect().then(response => {
            this.deptOptions = response.data;
          });
      },
       /** 查询地址列表 */
      getAddress(){
        listAddress().then(response=>{
          this.addressOptions = response.rows;
        })
      },
      /**获取用户列表*/
      getUsers(){
        listUser().then(response=>{
          this.userOptions = response.rows;
        })
      },
      /** 新增线路规划*/
      addLinePoi(){
        this.loading = true;
        let poi = {
          id:'',
          name:'',
          address:'',
          contacts:'',
          tel:'',
          lng:'',
          lat:'',
          deptId:'',
          pickupId:this.form.pickupId ? this.form.pickupId:'',
          dispatchId:this.form.dispatchId ? this.form.dispatchId:''
        }

        if(this.form.linePois && this.form.linePois.length > 0){
          //途经点
          let wayPoi = Object.assign({type:'1'},poi);
          this.form.linePois.push(wayPoi)
          this.loading = false;
        }else{
          this.form.linePois = [];
          //起点
          let startPoi = Object.assign({type:'0'},poi);
          //目的地
          let endPoi = Object.assign({type:'2'},poi);

          this.form.linePois.push(startPoi)
          this.form.linePois.push(endPoi)
          this.loading = false;
        }
      },
       /** 删除线路规划*/
      delLinePoi(scope){
        let index = scope.$index;
        let item = scope.row;
        if(item.type == '0'){
          this.$message.error('起点不可删除');
        }
        else if(item.type == '2'){
          this.$message.error('目的地不可删除');
        }
        else{
          if(item.id){
            delLinePoi(item.id)
          }
          this.form.linePois.splice(index,1)
          this.$refs.amap.initMap()
          this.drawDriving(this.form.linePois)
        }
      },
      //地址选择
      addressSearch(queryString,cb){
        var restaurants = this.addressOptions;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.addr.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      addressSelect(item,row){
        row.lat = item.lat;
        row.lng = item.lng;

        Object.keys(row).forEach(key=>{
          if(key != 'type' && key != 'id'){
            	row[key] = item[key] == undefined ? row[key] : item[key]
          }
          if(item['id']){
            row['addressId'] = item['id'];
          }
          if(item['clientId']){
            row['clientId'] = item['clientId'];
          }
				})
        this.$refs.amap.initMap()
        this.drawDriving(this.form.linePois)
      },
      drawDriving(linePois){
        this.markerList = [];
        let line = {};
        let waypoints = [];
        linePois.forEach(item=>{
          if(item.type == '0'){
            let origin = [parseFloat(item.lng),parseFloat(item.lat)]
            line.origin = origin;
          }
          if(item.type == '1'){
            let ways = [parseFloat(item.lng),parseFloat(item.lat)]
            waypoints.push(ways)
          }
          if(item.type == '2'){
            let destination = [parseFloat(item.lng),parseFloat(item.lat)]
            line.destination = destination;
          }
        })
        line.waypoints = waypoints;
        this.markerList.push(line)
      },

      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          carrierId: undefined,
          deptId: undefined,
          name: undefined,
          type: "0",
          status: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFlag: undefined
        };
        this.resetForm("form");
      },

      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.id != null) {
              updateLines(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.close()
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addLines(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.close()
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 关闭按钮 */
      close() {
        const obj = {
          path: "/tms/lines",
          query: { t: Date.now(), pageNum: this.$route.query.pageNum },
        };
        this.$tab.closeOpenPage(obj);
      },
    }
  }
</script>

<style lang="scss" scoped>
  .input-width{
    width: 214px;
  }

  .mainDiv {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
  .main_container {
    width: 100%;
    height: 100%;
  }
  .el-card {
    margin-bottom: 5px;
  }
  .el-footer {
    background-color: #ffffff;
    color: #333;
    text-align: right;
    line-height: 60px;
    border-top: 1px solid #e6ebf5;
    box-shadow: 0px 0px 10px #cdcdcd;
    z-index: 1000;
  }
  .footer-class {
    text-align: right;
    margin-top: 15px;
  }
  //顶部距离css
  .topItem {
    margin-bottom: 0px;
  }
  .areaSelect {
    width: 100%;
    padding-right: 5px;
  }
</style>
